import React, { useEffect, useState } from 'react'
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Spin } from 'antd';
import LeftTop from '../components/left-top'
import LeftBottom from '../components/left-bottom'
import RightTop from '../components/right-top'
import RightBottom from '../components/right-bottom'

import EmergencyLeftTop from '../components/emergency-left-top'
import EmergencyLeftBottom from '../components/emergency-left-bottom'
import EmergencyRightTop from '../components/emergency-right-top'
import EmergencyRightBottom from '../components/emergency-right-bottom'
import Weather from '../components/weather'
import Gis from './gis';
import moment from 'moment';
import './style.less'
import { FullScreenContainer } from '$components'
import { useFsRequest } from '$utils';
function homePage(props) {
    const { dispatch, actions } = props;
    const {
        waterLogin, getWaterLevelTrend, getWaterStructures, getWaterVideoList, getYsAccessToken, getWaterAlarms,
        worksafetyLogin, getEmerOrgList, getEmerTeamList, getEmerExpertList, getEmerMedicalList, getEmerRefugeList,
        getPumpStatus,
    } = actions.waterprevention;
    const childStyle = { height: '49%', color: '#fff', marginBottom: 17 }
    const cardHeight = document.body.clientHeight * 0.896 * 0.32
    const cardContentHeight = cardHeight - 42 - 13
    const [tab, setTab] = useState('overview');// overview   emergency
    const [emengencyTab, setEmengencyTab] = useState('yjjg');
    const [trendData, setTrendData] = useState([]);
    const [videoList, setVideoList] = useState([]);
    const [accessToken, setAccessToken] = useState('');
    const [structures, setStructures] = useState([]);
    const [waterLevelAlarms, setWaterLevelAlarms] = useState([]);
    const [emerResource, setEmerResource] = useState([]);
    const [spinning, setSpinning] = useState(true)
    const { data: emergencyList = {} } = useFsRequest({ url: 'water/emergency' });
    const SCREEN_COMPONENTS = {
        overview: { leftTop: LeftTop, leftBottom: LeftBottom, rightTop: RightTop, rightBottom: RightBottom },
        emergency: {
            leftTop: EmergencyLeftTop, leftBottom: EmergencyLeftBottom,
            rightTop: EmergencyRightTop,
            rightBottom: null
        }
    }
    const currentContainer = SCREEN_COMPONENTS[tab];

    useEffect(() => {
        getWaterData();
        setTimeout(() => {
            setSpinning(false)
        }, 8 * 1000);
    }, [])

    // 获取水务数据
    const getWaterData = async () => {
        const waterToken = sessionStorage.getItem('waterToken')
        let token = waterToken;
        if (!token) {
            try {
                const loginRes = await dispatch(waterLogin({ username: "123456", password: "shuiwu123_", pcode: 'fce4afe2-5b6a-408a-ab18-a2afa7fa027c' }))
                if (loginRes.success) {
                    sessionStorage.setItem('waterToken', loginRes.payload.data.token);
                    token = loginRes.payload.data.token;
                } else {
                    return;
                }
            } catch (error) {
                return;
            }
        }
        // 水位趋势
        dispatch(getWaterLevelTrend({ orgId: 84, keyword: '', token })).then(trendRes => {
            let fifterData = []
            if (trendRes.success) {
                trendRes.payload.data.map((item, index) => {
                    let alert = item.alert ? item.alert.replace('(', '').replace(')', '').split(',')[0] : '--'
                    let historyMax = item.historyMax ? item.historyMax.replace('(', '').replace(')', '').split(',')[0] : '--'
                    let waterLevel = item.data.length != 0 ? item.data[item.data.length - 1].waterLevel : ''
                    let lastWaterLevel = item.data.length != 0 ? item.data[item.data.length - 2].waterLevel : ''
                    let currentTime = item.data.length != 0 ? moment(item.data[item.data.length - 1].time).format('YYYY-MM-DD HH:mm:ss') : ''
                    let currentState = item.data.length != 0 ? (item.alert && alert <= waterLevel ? '超警戒' : '正常') : ''
                    let futureState = ''
                    if (item.alert && item.futureData && item.futureData.length != 0) {
                        item.futureData.map((futureItem) => {
                            if (futureItem.value >= alert && futureItem == '') {
                                futureState = `超警戒，预计${futureItem.forecast_time}时水位抵达${(futureItem.value)?.toFixed(2)}m`
                            }
                        })
                        futureState = futureState != '' ? futureState : '正常'
                    }
                    fifterData.push({
                        index: index + 1,
                        name: item.name,
                        currentState,
                        waterLevel,
                        lastWaterLevel,
                        currentTime,
                        alert,
                        historyMax,
                        futureState,
                        lat: item.latitude,
                        lng: item.longitude,
                        id: item.id
                    })
                })
            }
            setTrendData(fifterData)
        })
        // 结构物
        dispatch(getWaterStructures({ token })).then(structRes => {
            if (structRes.success) {
                setStructures(structRes.payload.data);
                // 视频
                let promiseArr = [
                    dispatch(getWaterVideoList(structRes.payload.data?.map(s => s.id).join(), { token })),
                    dispatch(getYsAccessToken({ token }))
                ];
                // Promise.all(promiseArr).then(resArr => {
                //     if (resArr[0].success && resArr[1].success) {
                //         const at = resArr[1].payload.data.accessToken;
                //         const list = resArr[0].payload.data?.map(v => ({ url: v.yingshi.hlsAddress, name: v.name, structId: v.structId }));
                //         setAccessToken(at)
                //         let videoTop = list?.find(x => x.name == '玉湖公园')
                //         setVideoList([videoTop].concat(list?.filter(v => v.name != '玉湖公园')));
                //         // setVideoList(list);
                //     }
                // })
                dispatch(getWaterVideoList(structRes.payload.data?.map(s => s.id).join(), { token })).then(resArr => {
                    const list = resArr.payload.data?.map(v => ({ url: v.yingshi.hlsAddress, name: v.name, structId: v.structId }));
                    let videoTop = list?.find(x => x.name == '玉湖公园')
                    setVideoList([videoTop].concat(list?.filter(v => v.name != '玉湖公园')));
                })
                dispatch(getYsAccessToken({ token })).then(resArr => {
                    const at = resArr.payload.data?.accessToken;
                    setAccessToken(at)
                })

                // 告警
                dispatch(getWaterAlarms({ token })).then(alarmRes => {
                    if (alarmRes.success) {
                        let levelAlarms = [];
                        alarmRes.payload.data.alarms.forEach(a => {
                            let alarm = { ...a }
                            for (const struct of structRes.payload.data) {
                                if (struct.id === a.structureId && struct.type.name === '河流') {
                                    alarm.lng = struct.longitude;
                                    alarm.lat = struct.latitude;
                                    levelAlarms.push(alarm);
                                }
                            };
                        })
                        setWaterLevelAlarms(levelAlarms);
                        setSpinning(false)
                    }
                })
            }
        })
    }

    const getPumpStatusData = async (structId) => {
        return await dispatch(getPumpStatus(structId));
    }

    return <>

        <FullScreenContainer>
            <div className='homepage'>
                <div className='_title'>
                    <div className='water_title_text'>
                        防汛提前知
                    </div>
                    <Weather />

                    <div onClick={() => { dispatch(push('/homepage')) }} className='_exit' > <Spin spinning={spinning}>返回平台 </Spin></div>

                </div>
                <div className='homepage-left homepage-left-left'>
                    <div div className="list">
                        <div className='child' style={childStyle} >
                            <currentContainer.leftTop />
                        </div>
                        <div className='child' style={childStyle} >
                            <currentContainer.leftBottom waterLevelLength={trendData.length} waterLevelAlarms={waterLevelAlarms} />
                        </div>
                    </div>
                </div>
                <div className='homepage-center'>
                    <Gis
                        changeTab={(e) => {
                            setTab(e)
                        }}
                        changeEmengencyTab={(e) => {
                            setEmengencyTab(e)
                        }}
                        trendData={trendData}
                        waterLevelAlarms={waterLevelAlarms}
                        emerResource={emerResource}
                        emergencyList={emergencyList}
                        getPumpStatusData={getPumpStatusData}
                    />
                </div>
                <div className='homepage-left homepage-left-right'>
                    <div div className="list">
                        <div className='child-right' style={{ ...childStyle, height: tab == 'emergency' ? '100%' : '49%' }} key={tab}>
                            <currentContainer.rightTop emergencyList={emergencyList} emengencyTab={emengencyTab} emerResource={emerResource} trendData={trendData} />
                        </div>
                        {currentContainer.rightBottom && <div className='child-right' style={childStyle}>
                            <currentContainer.rightBottom structures={structures} videoList={videoList} accessToken={accessToken} />
                        </div>}
                    </div>
                </div>
            </div >
        </FullScreenContainer>



    </>
}

function mapStateToProps(state) {
    const {
        auth, global
    } = state;
    return {
        clientHeight: global.clientHeight,
        actions: global.actions,
    };
}

export default connect(mapStateToProps)(homePage);


